<?php

namespace RedMVC;

/**
 * Auth class
 *
 * @category    RedMVC
 * @author      Jan Fischer, bitWorking <info@bitworking.de>
 */
class Auth{

    protected static $_adapter;
    protected static $_storage;

    /**
     * sets auth adapter
     *
     * @param Auth\Adapter\IAdapter $adapter
     */
    public static function setAdapter(Auth\Adapter\IAdapter $adapter){
        self::$_adapter = $adapter;
    }

    /**
     * sets auth storage
     *
     * @param Auth\Storage\IStorage $storage
     */
    public static function setStorage(Auth\Storage\IStorage $storage){
        self::$_storage = $storage;
    }

    /**
     * gets auth storage
     *
     * @return Auth\Storage\IStorage
     */
    protected static function _getStorage(){
        if(null === self::$_storage){
            self::$_storage = new Auth\Storage\Session();
        }
        return self::$_storage;
    }

    /**
     * login
     *
     * @return bool
     */
    public static function login(){
        if(null !== self::$_adapter){
            return self::$_adapter->login();
        }
        throw new \Exception('Auth: No adapter set');
    }

    /**
     * logout
     */
    public static function logout(){
        self::_getStorage()->clear();
    }

    /**
     * saves identity data
     *
     * @param array $authData
     */
    public static function saveIdentity(array $authData){
        self::_getStorage()->write($authData);
    }

    /**
     * returns if is logged in
     *
     * @return bool
     */
    public static function hasIdentity(){
        return self::_getStorage()->hasAuthData();
    }

    /**
     * gets identity data
     *
     * @return array
     */
    public static function getIdentity(){
        return self::_getStorage()->read();
    }

}